layui.define(['layer', 'table', 'element', 'form', 'jquery' , 'laydate' , 'layarea','dtree'], function (exports) {
    // noinspection SpellCheckingInspection
    var layer = layui.layer //弹层
        , table = layui.table //表格
        , element = layui.element //元素操作
        , $ = layui.jquery
        , layarea = layui.layarea
        , form = layui.form
        , laydate = layui.laydate
        , dtree = layui.dtree;

    var birthday_date = null;
    var form_province  ;
    var form_city  ;
    var form_county ;
    var operationHospitalId;
    // var firstLoadId = ['1'];
    var loadDtreeCount = 'firstLoad';
    task = {

        init_listen_dtree_click:function(){
            // 绑定节点点击
            dtree.on("node('demoTree')" ,function(obj){
                layer.msg(JSON.stringify(obj.param));
            });
        },

        init_dept_dtree:function(treeData,operationHospitalId){

            if (loadDtreeCount === 'firstLoad'){
                // 初始化树dtree renderSelect render
                var DemoTree = dtree.render({
                    elem: "#DeptDtree",
                    checkbar: true,
                    checkbarType: "all",
                    // width: "100%",
                    data:  treeData,
                });
                loadDtreeCount = 'againLoadDtree';
            }else {
                //重新加载渲染
                dtree.reload( 'DeptDtree',{
                    checkbar: true,
                    checkbarType: "all",
                    data:  treeData
                });
            }
        },

        //医院表格初始化
        init_hospital_table: function () {
            task_table_Info = table.render({
                elem: '#task_table', //选取html表格的id
                id: 'task_table_Id',
                response: {
                    statusCode: '200 ' //规定成功的状态码，默认：0
                }
                , url: '/task/getAllTask'
                , title: '任务表'
                , toolbar: '#task_table_top'
                , page: true
                , cols: [[
                    /*{type: 'checkbox', fixed: 'left'}
                    , */{field: 'taskName', title: '任务名称', align: 'center', sort: true, fixed: 'left'}
                    , {field: 'status', title: '审批状态', align: 'center', sort: true, fixed: 'left',templet: function (row){
                            if (row.status!==undefined){
                                switch (row.status) {
                                    case 0:
                                        return "新建";
                                    case 1:
                                        return "审核中";
                                    case 2:
                                        return "审核通过";
                                    case 3:
                                        return "未通过";
                                    default:
                                        return "";
                                }
                            }else {
                                return "/";
                            }
                        }}
                    ,{
                        field: 'createBy',
                        title: '创建人 ',
                        align: 'center',
                        sort: true,
                        fixed: 'left',
                    }
                    , {field: 'createTime', title: '创建时间', align: 'center', sort: true, fixed: 'left'}
                    , {field: 'employeeAddress', title: '操作日志', align: 'center', sort: true, fixed: 'left'}
                    , {fixed: 'tool', title: '操作', width: 165, align: 'center', toolbar: '#task_table_right'}
                ]]
            });
        },

        //监听表格行工具事件   tool是行工具条
        init_listen_table_tool() {
            table.on('tool(task_table)', function (obj) { //注：tool 是工具条事件名，demo 是 table 原始容器的属性 lay-filter="对应的值"

                var data = null;
                data = obj.data;//获得当前行数据
                alert(JSON.stringify(data));
                var layEvent = obj.event; //获得 lay-event 对应的值
                if (layEvent === 'detail_task') {
                    task.init_task_detial(data,'detail');
                } else if (layEvent === 'delete_task') {
                    //任务单行删除
                    task.delete_task(data);
                } else if (layEvent === 'edit_task') {
                    //任务编辑
                    alert(JSON.stringify(data));
                    task.init_hospital_form('edit', data);
                }else if (layEvent === 'assignment_task_dept') {
                    //任务编辑
                    task.init_hospital_dept( data);
                }

            });
        },

        //监听表格头工具条事件 toolbar是头工具条
        /*init_listen_table_toolbar() {
            table.on('toolbar(task_table)', function (obj) {
                var checkStatus = table.checkStatus("task_table_Id") //hospital_table_Id来自layui 初始化表格ID
                    , choose_data = checkStatus.data; //获取选中的数据
                switch (obj.event) {
                    case 'add_task':
                        task.init_hospital_form('add', '');
                        break;
                    case 'batch_task_deleted':
                        task.batch_delete_hospital(choose_data);
                        break;
                }
            });
        },*/

        //监听表格头工具条事件 toolbar是头工具条
        init_listen_table_toolbar() {
            table.on('toolbar(task_table)', function (obj) {
                var checkStatus = table.checkStatus("task_table_Id") //employee_table_Id来自layui 初始化表格ID
                    , choose_data = checkStatus.data; //获取选中的数据
                switch (obj.event) {
                    case 'add_task':
                        task.init_hospital_form('add', undefined);
                        break;
                    case 'batch_task_deleted':
                        task.batch_delete_hospital(choose_data);
                        break;
                    case 'assignment_task_job':
                        task.assignment_employee_job(choose_data);
                        break;
                }
            });
        },


        init_task_detial: function (data,type) {
            var form_title = '任务详情';
            $.get('/manage/form/detial_task.html', function (html) {
                nowIndex = layer.open(  //弹出层
                    {
                        type: 1,
                        title: form_title,
                        area: ['900px', '600px'],
                        btnAlign: 'c',//按钮居中对齐
                        // content: $('#edit_hospital_form'),
                        content: html,
                        anim: 5,//弹出效果 渐显
                        shift: -1,
                        btn: ['提交', '关闭'],
                        yes: function (index, layero) {
                            form.on('submit(detial_task)',function(){
                                task.submit_form(data,type);
                                return false;
                            });
                        },
                        btn2: function () {
                        },
                        success: function (layero,index) {

                            if (type === 'detail') {
                                alert(JSON.stringify(data));
                                $("#taskName").val(data.taskName);
                                $("#content").val(data.content);
                                $("#integral").val(data.integral);
                                var list = data.accessories;
                                for ( var k in list) {
                                    /*$("#demoList").append('<tr>'
                                        , '<td><img  src="../../../' + list[k].filePath + '"  width="160" height="100" style="white-space:nowrap"></td>'
                                        , '</tr>');*/
                                    $("#demoList1").append('&nbsp<img  src="../../../'+list[k].filePath+'"  width="160" height="125" style="white-space:nowrap">&nbsp');
                                    console.log(list[k].filePath);
                                    /*var status = data.status;
                                    status === 1 ? status = true :status = false;
                                    $("#status").prop("checked",status);
                                    task.edit_area_form(data);*/
                                    form.render();
                                }
                            }else {
                                task.init_date_form();
                                task.init_area_form();
                            }

                            layero.addClass('layui-form');//添加form标识
                            layero.find('.layui-layer-btn0').attr('lay-filter','detial_task').attr('lay-submit','');//将按钮弄成能提交的
                            form.render();
                        },
                    });
            })
        },

        //打开新增/编辑弹框，这一层主要负责是否给编辑框赋值--->打开弹出层参数 type 类型 ,data 编辑改行的数据
        init_hospital_form: function (type, data) {
            var form_title = '';
            type === 'add' ? form_title = "添加任务信息" : form_title = "编辑任务信息";
            $.get('/manage/form/edit_task.html', function (html) {
                nowIndex = layer.open(  //弹出层
                    {
                        type: 1,
                        title: form_title,
                        area: ['900px', '600px'],
                        btnAlign: 'c',//按钮居中对齐
                        // content: $('#edit_hospital_form'),
                        content: html,
                        anim: 5,//弹出效果 渐显
                        shift: -1,
                        btn: ['保存', '关闭'],
                        yes: function (index, layero) {
                            form.on('submit(submit_task)',function(){
                                task.update_form(type,data);
                                return false;
                            });
                        },
                        btn2: function () {
                        },
                        success: function (layero,index) {

                            if (type === 'edit') {
                                $("#taskName").val(data.taskName);
                                $("#content").val(data.content);
                                $("#integral").val(data.integral);
                                var list = data.accessories;
                                for ( var k in list) {
                                    $("#demoList").append('<tr>'
                                        /*,'<input type="checkbox" id="deleteId" value="'+list[k].id+'"/>'*/
                                        ,'<td><img  src="../../../'+list[k].filePath+'"  width="160" height="100"></td>'
                                        ,'<td></td>'
                                        ,'<td></td>'
                                        ,'<td><a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" onclick="deletepic(this,\''+list[k].id+'\')">删除</ a></td>'
                                        ,'</tr>');
                                    console.log(list[k].filePath);
                                }
                                /*var status = data.status;
                                status === 1 ? status = true :status = false;
                                $("#status").prop("checked",status);
                                task.edit_area_form(data);*/
                                form.render();
                            }else {
                                task.init_date_form();
                                task.init_area_form();
                            }

                            layero.addClass('layui-form');//添加form标识
                            layero.find('.layui-layer-btn0').attr('lay-filter','submit_task').attr('lay-submit','');//将按钮弄成能提交的
                            form.render();

                        },

                    });
            })
        },

        /**
         * 获取所有部门-科室的dtree树  传递医院Id
         * @return
         */
        init_hospital_dept:function(rowData){
            operationHospitalId = rowData.id;
            nowIndex = layer.open(
                {
                    type: 1,
                    title: '部门管理',
                    area: ['550px', '400px'],
                    btnAlign: 'c',//按钮居中对齐
                    content: $("#assignment_hospital_dept"),
                    anim: 5,//弹出效果 渐显
                    success:function(index){
                        let treeData;
                        $.ajax({
                            url: "/manage/department/findDeptTreeList?&&hospitalId="+rowData.id,
                            type: "GET",
                            success: function (resp) {
                                if (resp.code === 200) {
                                    treeData = resp.data;
                                    task.init_dept_dtree(treeData,operationHospitalId);
                                }
                            }
                        });
                    }
                });
        },

        /*listen_assignment_hospital_dept_click:function(){
            $("#edit_hospital_dept").click(function () {
                let deptIds;
                let  checkList = dtree.getCheckbarNodesParam("DeptDtree");
                $.each(checkList, function (index, val) { //index是数组对象索引，val是对象
                    if (index === 0) {
                        deptIds = val.nodeId;
                    } else {
                        deptIds = deptIds + ',' + val.nodeId;
                    }
                });
                $.ajax({
                    url: '/manage/department/updateHospitalHaveDeptList',
                    contentType: "application/x-www-form-urlencoded",
                    type: 'POST',
                    data: {
                        hospitalId: operationHospitalId,
                        deptIds: deptIds
                    },
                    success: function (resp) {
                        if (resp.code === 200) {
                            layer.msg('保存成功', {icon: 1});
                            layer.close(nowIndex);
                        } else {
                            layui.form.render();
                            layer.msg("保存失败" + " " + resp.msg, {icon: 5});
                        }

                    }
                });

            });
        },*/

        //送审
        submit_form: function (data,type) {
            layer.confirm("是否提交[" + data.taskName + "]", function (index) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json",//设置请求参数类型为json字符串
                    url: "/task/submit?id=" + data.id,
                    success: function (resp) {
                        var code = resp.code;
                        if (code === 200) {
                            layer.msg('提交成功', {icon: 1});
                            task_table_Info.reload();
                        } else {
                            layer.msg("提交失败" + resp.msg, {icon: 5});
                        }
                    }
                });
                // layer.close(index);
                //向服务端发送删除指令
            });
        },

        //表单新增/编辑  新增就提交表单，编辑就赋值表单等待表单提交
        update_form: function (type, data) {
            // 请求方式处理和URL处理
            if (type === 'add') {
                request_method = 'POST';
                request_url = '/task/newTask';
            } else {
                request_method = 'PUT';
                request_url = '/task/updateTask/' + data.id;
            }
            var status = $("#status").prop("checked");
            status ? status = 1 : status = 0;
            var task_form_data = {
                taskName: $("#taskName").val(),
                content: $("#content").val(),
                integral: $("#integral").val(),
                hiddenFilePath: $("#hiddenFilePath").val(),

                province : form_province,
                city : form_city,
                area : form_county,
                status: status,
            };
            $.ajax({
                url: request_url,
                contentType: "application/json",
                type: request_method,
                data: JSON.stringify(task_form_data),
                success: function (resp) {
                    if (resp.code === 200) {
                        var data = resp.data;
                        form_province =undefined;
                        form_city=undefined;
                        form_county=undefined;
                        layer.msg('保存成功', {icon: 1});
                        layer.close(nowIndex);
                        task_table_Info.reload();
                    } else {
                        layui.form.render();
                        layer.msg("保存失败" + " " + resp.msg, {icon: 5});
                    }

                }
            });
        },

        //医院单行删除
        delete_task: function (data) {
            layer.confirm("是否删除[" + data.taskName + "]", function (index) {
                $.ajax({
                    type: "DELETE",
                    contentType: "application/json",//设置请求参数类型为json字符串
                    url: "/task/deletedOne/" + data.id,
                    success: function (resp) {
                        var code = resp.code;
                        if (code === 200) {
                            layer.msg('删除成功', {icon: 1});
                            task_table_Info.reload();
                        } else {
                            layer.msg("删除失败 " + resp.msg, {icon: 5});
                        }
                    }
                });
                layer.close(index);
                //向服务端发送删除指令
            });
        },

        //医院批量删除 choose_data选中的行数据
        batch_delete_hospital: function (choose_data) {
            if (choose_data.length === 0) {
                layer.msg('请选择一行');
            } else {
                var keyArr = '';
                var nameArr = '';
                $.each(choose_data, function (index, val) { //index是数组对象索引，val是对象
                    if (index === 0) {
                        keyArr = keyArr + val.id;
                        nameArr = nameArr + val.name;
                    } else {
                        keyArr = keyArr + ',' + val.id;
                        nameArr = nameArr + ',' + val.name;
                    }
                });

                layer.confirm('是否确定删除选中的数据[' + nameArr + "]",
                    {
                        icon: 0,
                        title: "提示",
                        skin: "deleteTips"
                    }
                    , function () {
                        $.ajax({
                            type: "POST",
                            contentType: "application/x-www-form-urlencoded",//设置请求参数类型为json字符串
                            url: "/manage/task/batchHospital",
                            data: {
                                ids: keyArr,
                                nameArr: nameArr
                            },
                            success: function (resp) {
                                var code = resp.code;
                                if (code === 200) {
                                    layer.msg('删除成功', {icon: 1});
                                    task_table_Info.reload();
                                } else {
                                    layer.msg("删除失败", {icon: 5});
                                }
                            }
                        });


                    });
            }
        },

        //时间工具组件
        init_date_form:function(value){
            laydate.render({
                elem: '#birthday' ,//指定元素
                trigger: 'click'
                ,theme: '#616261'
                ,value : value  //用于编辑回显给表单赋初值
                ,done: function(value, date, endDate){
                    // 编辑/添加选取过时间值，存放在变量birthday_date中
                    birthday_date = value;
                }
            });
        },

        //初始化省市联动表单
        init_area_form:function(){
            layarea.render({
                elem: '#area-picker',
                data: {
                    province: "请选择省",
                    city: "请选择市",
                    county: "请选择区",
                },
                change: function (res) {
                    form_province = res.province;
                    form_city =res.city;
                    form_county =res.county;
                }
            });
        },

        //编辑省市联动
        edit_area_form:function(row){
            layarea.render({
                elem: '#area-picker',
                data: {
                    province: row.province,
                    city: row.city,
                    county: row.county,
                },
                change: function (res) {
                    form_province = res.province;
                    form_city =res.city;
                    form_county =res.county;
                },
            });
        },

        // 表格页面监听表单中的switch改变发送请求
        listen_hospital_table_switch: function() {
            //监听行单击事件
            form.on('switch(hospital_table_Switch)', function(data){
                var switch_status = data.elem.checked?1:0;
                var row_data = JSON.parse( data.elem.getAttribute('row-data'));
                $.ajax({
                    url: "/manage/task/" + row_data.id,
                    contentType : "application/json",
                    type: 'PUT',
                    data:JSON.stringify( {status:switch_status}),
                    success: function (resp) {
                        if (resp.code===200){
                            var data = resp.data;
                            layer.msg('保存成功', {icon: 1});
                            task_table_Info.reload();
                        }else {
                            layui.form.render();
                            layer.msg("保存失败"+ " "+ resp.msg, {icon: 5});
                        }

                    }
                });

            });



        },

    };

    task.init_listen_dtree_click();
    task.init_hospital_table();
    task.init_date_form();
    task.listen_hospital_table_switch();
    task.init_listen_table_tool();
    task.init_listen_table_toolbar();
    task.listen_assignment_hospital_dept_click();
    task.init_task_detial();
    exports("task", task);


});